/*
 * TestDervyClnt.cpp
 *
 *  Created on: May 9, 2011
 *      Author: michael
 */

#include "Logger.h"

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <cstring>

using boost::asio::ip::tcp;

int main(int argc, char* argv[])
{
	try
	{
		/*if (argc != 2)
		{
			std::cerr << "Usage: client <host>" << std::endl;
			return 1;
		}*/

		boost::asio::io_service io_service;

		tcp::resolver resolver(io_service);
		tcp::resolver::query query("localhost", "7788");
		tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
		tcp::resolver::iterator end;

		tcp::socket socket(io_service);
		boost::system::error_code error = boost::asio::error::host_not_found;
		while (error && endpoint_iterator != end)
		{
			socket.close();
			socket.connect(*endpoint_iterator++, error);
		}
		if (error)
			throw boost::system::system_error(error);

		for (;;)
		{
			std::cout << "communicating started.. " << std::endl;

			boost::system::error_code error;

			std::string str("Hello, server!");
			size_t strlen = str.size();
			size_t l1 = socket.write_some(boost::asio::buffer(&strlen, sizeof(strlen)), error);
			size_t l2 = socket.write_some(boost::asio::buffer(str.c_str(), strlen), error);

			if (error == boost::asio::error::eof)
				break; // Connection closed cleanly by peer.
			else if (error)
				throw boost::system::system_error(error); // Some other error.

			int strlen1 = 0;
			size_t len = socket.read_some(boost::asio::buffer(&strlen1, sizeof(strlen1)), error);
			std::vector<char> buf2;
			buf2.resize(strlen1);
			size_t len1 = socket.read_some(boost::asio::buffer(buf2), error);

			if (error == boost::asio::error::eof)
				break; // Connection closed cleanly by peer.
			else if (error)
				throw boost::system::system_error(error); // Some other error.

			std::cout << "read_some: ";
			std::cout.write(buf2.data(), len1);
			std::cout << std::endl;

			std::cout << "communicating finished.. " << std::endl;
		}
	} catch (std::exception& e)
	{
		std::cerr << "Error occured: " << e.what() << std::endl;
	}

	return 0;
}

